package com.ypf.accesslimit.limit;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

@Component
public class GenerateRedisKey {
    /**
     * 把请求路径转换为Redis中存储的key值
     * @param joinPoint
     * @return
     */
    public String getMethodUrlConvertRedisKey(ProceedingJoinPoint joinPoint){
        StringBuilder redisKey = new StringBuilder("");
        Method m = ((MethodSignature)joinPoint.getSignature()).getMethod(); // 获得被修饰的方法对象
//        GetMapping methodAnnotation = m.getAnnotation(GetMapping.class);
        String[] methodValue =null;

        // 为了保证能在所有接口的类型上使用 所以要判断所有的类型
        if (m.getAnnotation(GetMapping.class)!=null){  // 判断该方法上是否有GetMapping这个注解
            methodValue = m.getAnnotation(GetMapping.class).value();

        }else if (m.getAnnotation(PostMapping.class)!=null){
            methodValue = m.getAnnotation(PostMapping.class).value();

        }else if (m.getAnnotation(PutMapping.class)!=null){
            methodValue = m.getAnnotation(PutMapping.class).value();

        }else if (m.getAnnotation(DeleteMapping.class)!=null){
            methodValue = m.getAnnotation(DeleteMapping.class).value();
        }else {
            methodValue = m.getAnnotation(RequestMapping.class).value();
        }

        String decUrl = diagonalLineToCamel(methodValue[0]);
        redisKey.append("interfaceIsLimit:").append(decUrl).toString();
        return redisKey.toString();
    }

    /**
     * 输入一个url 如 /hello/world  返回一个 HelloWorld
     * @param param
     * @return
     */
    private String diagonalLineToCamel(String param){
        char UNDERLINE = '/';
        if (param==null||"".equals(param.trim())){
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0;i<len;i++){
            char c = param.charAt(i);
            if (c==UNDERLINE){
                if (++i<len){
                    // 只要不是最后一个就把下划线的下一个字母转换为大写
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            }else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

}
